package com.google.code.sip.ucenter.ws.resources;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.apache.commons.lang.StringUtils;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.Authentication;
import org.jasig.cas.authentication.principal.Credentials;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.util.HttpClient;
import org.jasig.cas.validation.Assertion;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.code.sip.ucenter.model.Role;
import com.google.code.sip.ucenter.model.User;
import com.google.code.sip.ucenter.model.UserCustomProfile;
import com.google.code.sip.ucenter.model.UserEvent;
import com.google.code.sip.ucenter.model.UserProfile;
import com.google.code.sip.ucenter.service.FriendGroupManager;
import com.google.code.sip.ucenter.service.RoleManager;
import com.google.code.sip.ucenter.service.UserManager;
import com.google.code.sip.ucenter.utils.StringRegexUtils;
import com.google.code.sip.ucenter.ws.WSResponse;
import com.google.code.sip.ucenter.ws.WSResponseStatus;
import com.google.code.sip.ucenter.ws.dto.UserCustomProfileDto;
import com.google.code.sip.ucenter.ws.dto.UserDto;
import com.google.code.sip.ucenter.ws.dto.UserProfileDto;
import com.sun.jersey.spi.resource.Singleton;

@Component
@Path("/user")
@Singleton
@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public class UserResource extends AbstractResource {
	private static final Logger logger = LoggerFactory
			.getLogger(UserResource.class);

	private static final String PARAM_SERVICE_URL = "service";
	private static final String DEFAULT_SERVICE_PATH_INFO = "/defaultService";

	private String defaultService = null;

	@Autowired
	private CentralAuthenticationService centralAuthenticationService;
	@Autowired
	private UserManager userManager;
	@Autowired
	private RoleManager roleManager;
	@Autowired
	private FriendGroupManager friendGroupManager;

	/** CookieGenerator for the TicketGrantingTickets. */
	@Autowired
	private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;

	@Autowired
	private HttpClient httpClient;

	@POST
	@Path("get")
	public WSResponse<UserDto> getUser(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user != null && !user.isDeleted()) {
				UserDto userDto = toDto(user);
				return new WSResponse<UserDto>(userDto);
			} else if (user == null) {
				return new WSResponse<UserDto>(new WSResponseStatus(-1,
						"该用户不存在"));
			} else {
				return new WSResponse<UserDto>(new WSResponseStatus(-2,
						"该用户已删除"));
			}
		} catch (RuntimeException e) {
			logger.error("called getUser method error userId:" + userId, e);
			return new WSResponse<UserDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("getByName")
	public WSResponse<UserDto> getUserByName(
			@FormParam("username") String username) {
		assert (null != username) : "username cann't be null.";
		try {
			User user = userManager.getUserByName(username);
			if (user != null && !user.isDeleted()) {
				UserDto userDto = toDto(user);
				return new WSResponse<UserDto>(userDto);
			} else if (user == null) {
				return new WSResponse<UserDto>(new WSResponseStatus(-1,
						"该用户不存在"));
			} else {
				return new WSResponse<UserDto>(new WSResponseStatus(-2,
						"该用户已删除"));
			}
		} catch (RuntimeException e) {
			logger.error("called getUserByName method error username:"
					+ username, e);
			return new WSResponse<UserDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("getByTicket")
	public WSResponse<UserDto> getUserByTicket(
			@FormParam("grantingTicket") String grantingTicket,
			@FormParam("service") String service) {
		assert (null != grantingTicket) : "grantingTicket cann't be null.";
		Assertion assertion = null;
		try {
			SimpleWebApplicationServiceImpl appService = new SimpleWebApplicationServiceImpl(
					genService(service), httpClient);
			String serviceTicketId = centralAuthenticationService
					.grantServiceTicket(grantingTicket, appService);
			assertion = centralAuthenticationService.validateServiceTicket(
					serviceTicketId, appService);
		} catch (TicketException e) {
			logger.error("无效ticket", e);
		}
		if (assertion == null) {
			return new WSResponse<UserDto>(
					new WSResponseStatus(-1, "该票据无效或已过期"));
		}
		List<Authentication> authentications = assertion
				.getChainedAuthentications();
		String username = null;
		if (authentications != null && !authentications.isEmpty()
				&& authentications.get(0).getPrincipal() != null) {
			username = authentications.get(0).getPrincipal().getId();
		}
		if (StringUtils.isBlank(username)) {
			return new WSResponse<UserDto>(
					new WSResponseStatus(-1, "该票据无效或已过期"));
		}
		User user = null;
		try {
			if (StringRegexUtils.isEmail(username)) {
				user = userManager.getUserByEmail(username);
			} else {
				user = userManager.getUserByName(username);
				// 根据火秀号查用户
				if (user == null) {
					user = userManager.getUserByHuoshowId(username);
				}
			}
		} catch (RuntimeException e) {
			printErrorMsg(e, username);
		}
		if (user != null && !user.isDeleted()) {
			UserDto userDto = toDto(user);
			return new WSResponse<UserDto>(userDto);
		} else if (user == null) {
			return new WSResponse<UserDto>(new WSResponseStatus(-2, "该用户不存在"));
		} else {
			return new WSResponse<UserDto>(new WSResponseStatus(-3, "该用户已删除"));
		}
	}

	@POST
	@Path("checkUsername")
	public WSResponse<String> checkUsername(
			@FormParam("username") String username) {
		assert (null != username) : "username cann't be null.";
		try {
			if (!isValidUsername(username)) {
				return new WSResponse<String>(new WSResponseStatus(-1, "用户名非法"));
			}
			if (isUsernameHasBadword(username)) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"包含不允许注册的词语"));
			}
			if (userManager.getUserByName(username) != null) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"用户名已被使用"));
			}
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called checkUsername method error username:"
					+ username, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("checkPassword")
	public WSResponse<String> checkPassword(
			@FormParam("password") String password) {
		assert (null != password) : "password cann't be null.";
		try {
			if (!isValidPassword(password)) {
				return new WSResponse<String>(new WSResponseStatus(-1, "该密码非法"));
			}
			return new WSResponse<String>();
		} catch (Exception e) {
			logger.error("called checkPassword method error password:"
					+ password, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("checkEmail")
	public WSResponse<String> checkEmail(@FormParam("email") String email) {
		assert (null != email) : "email cann't be null.";
		try {
			if (!isValidEmail(email)) {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该邮箱格式有误"));
			}
			if (isEmailInBlacklist(email)) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"该邮箱不允许注册"));
			}
			List<User> users = userManager.findUser("email", email);
			if (users != null && !users.isEmpty()) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"该邮箱已用于注册"));
			}
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called checkEmail method error email:" + email, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("updateProfile")
	public WSResponse<String> updateUserProfile(UserProfileDto profileDto) {
		// assert (null != userId) : "userId cann't be null.";
		assert (null != profileDto) : "profileDto cann't be null.";
		assert (null != profileDto.getUserId()) : "userId cann't be null.";
		try {
			User user = userManager.getUser(profileDto.getUserId());
			if (user == null) {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			UserProfile profile = new UserProfile();
			BeanUtils.copyProperties(profileDto, profile);
			profile.setUser(user);
			userManager.saveUserProfile(profile);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(
					"called updateUserProfile method error UserProfileDto:"
							+ profileDto, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("getProfile")
	public WSResponse<UserProfileDto> getUserProfile(
			@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			UserProfile profile = userManager.getProfile(userId);
			if (profile != null) {
				UserProfileDto dto = new UserProfileDto();
				BeanUtils.copyProperties(profile, dto);
				return new WSResponse<UserProfileDto>(dto);
			} else {
				return new WSResponse<UserProfileDto>(new WSResponseStatus(-1,
						"指定用户的详细信息不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called getUserProfile method error userId:" + userId,
					e);
			return new WSResponse<UserProfileDto>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("updateCustomProfile")
	public WSResponse<String> updateCustomProfile(
			@FormParam("userId") String userId, @FormParam("name") String name,
			@FormParam("value") String value) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != name) : "name cann't be null.";
		assert (null != value) : "value cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			UserCustomProfile profile = userManager.getUserCustomProfile(user,
					name);
			if (profile == null) {
				profile = new UserCustomProfile();
				profile.setUser(user);
				profile.setValue(value);
			} else {
				profile.setValue(value);
			}
			userManager.saveUserCustomProfile(profile);
			return new WSResponse<String>();

		} catch (RuntimeException e) {
			logger.error("called updateCustomProfile method error userId:"
					+ userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("getCustomerProfile")
	public WSResponse<UserCustomProfileDto> getUserCusomerProfile(
			@FormParam("userId") String userId, @FormParam("name") String name) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != name) : "name cann't be null.";

		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<UserCustomProfileDto>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			UserCustomProfile profile = userManager.getUserCustomProfile(user,
					name);
			if (profile != null) {
				UserCustomProfileDto dto = new UserCustomProfileDto();
				BeanUtils.copyProperties(profile, dto);
				dto.setUserId(profile.getUser().getId());
				return new WSResponse<UserCustomProfileDto>(dto);
			} else {
				return new WSResponse<UserCustomProfileDto>(
						new WSResponseStatus(-2, "该自定义信息不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called getUserCusomerProfile method error userId:"
					+ userId, e);
			return new WSResponse<UserCustomProfileDto>(
					WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("getCustomerProfiles")
	public WSResponse<UserCustomProfileDto> getUserCusomerProfiles(
			@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user == null) {
				return new WSResponse<UserCustomProfileDto>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			List<UserCustomProfile> profiles = userManager
					.getUserCustomProfiles(user);
			if (profiles != null && !profiles.isEmpty()) {
				List<UserCustomProfileDto> dtoList = new ArrayList<UserCustomProfileDto>(
						profiles.size());
				for (UserCustomProfile profile : profiles) {
					UserCustomProfileDto dto = new UserCustomProfileDto();
					BeanUtils.copyProperties(profile, dto);
					dto.setUserId(profile.getUser().getId());
					dtoList.add(dto);
				}
				return new WSResponse<UserCustomProfileDto>(dtoList);
			} else {
				return new WSResponse<UserCustomProfileDto>(
						new WSResponseStatus(-2, "该用户与应用的自定义信息不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called getUserCusomerProfiles method error userId:"
					+ userId, e);
			return new WSResponse<UserCustomProfileDto>(
					WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("register")
	public WSResponse<String> registerUser(UserDto userDto) {
		assert (null != userDto) : "user cann't be null.";
		try {
			if (!isValidUsername(userDto.getUsername())) {
				return new WSResponse<String>(new WSResponseStatus(-1, "用户名非法"));
			}
			if (isUsernameHasBadword(userDto.getUsername())) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"包含不允许注册的词语"));
			}
			if (!isValidPassword(userDto.getPassword())) {
				return new WSResponse<String>(new WSResponseStatus(-4, "密码非法"));
			}
			if (!isValidEmail(userDto.getEmail())) {
				return new WSResponse<String>(
						new WSResponseStatus(-5, "邮箱格式有误"));
			}
			if (isEmailInBlacklist(userDto.getEmail())) {
				return new WSResponse<String>(new WSResponseStatus(-6,
						"邮箱不允许注册"));
			}
			if (userManager.getUserByName(userDto.getUsername()) != null) {
				return new WSResponse<String>(new WSResponseStatus(-3,
						"用户名已被使用"));
			}
			if (userManager.getUserByEmail(userDto.getEmail()) != null) {
				return new WSResponse<String>(new WSResponseStatus(-7,
						"邮箱已用于注册"));
			}
			if (StringUtils.isNotBlank(userDto.getHuoshowId())
					&& userManager.getUserByHuoshowId(userDto.getHuoshowId()) != null) {
				return new WSResponse<String>(
						new WSResponseStatus(-8, "火秀号被使用"));
			}
			User user = new User();
			BeanUtils.copyProperties(userDto, user);
			// 设置角色
			Role role = roleManager.getRoleByName("NORMAL");
			if (role != null) {
				user.setRole(role);
			}
			userManager.saveUser(user);

			// 创建默认及常用好友组
			friendGroupManager.createdCommonGroups(user);
			return new WSResponse<String>(user.getId());
		} catch (RuntimeException e) {
			logger.error("called registerUser method error", e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("update")
	public WSResponse<String> updateUser(UserDto userDto) {
		assert (null != userDto) : "userDto cann't be null.";
		assert (null != userDto.getId()) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userDto.getId());
			if (user == null) {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			// 检查用户名的合法性、唯一性
			String username = userDto.getUsername();
			if (StringUtils.isNotBlank(username)) {
				if (!isValidUsername(username)) {
					return new WSResponse<String>(new WSResponseStatus(-2,
							"用户名非法"));
				}
				User userByName = userManager.getUserByName(username);
				if (userByName != null
						&& !userByName.getId().equals(user.getId())) {
					return new WSResponse<String>(new WSResponseStatus(-3,
							"用户名已使用。"));
				}
				user.setUsername(username);
			}
			// 检查邮箱的合法性、唯一性
			String email = userDto.getEmail();
			if (StringUtils.isNotBlank(email)) {
				if (!isValidEmail(email)) {
					return new WSResponse<String>(new WSResponseStatus(-4,
							"邮箱格式有误"));
				}
				if (isEmailInBlacklist(email)) {
					return new WSResponse<String>(new WSResponseStatus(-5,
							"邮箱不允许使用"));
				}
				User userByEmail = userManager.getUserByEmail(email);
				if (userByEmail != null
						&& !userByEmail.getId().equals(user.getId())) {
					return new WSResponse<String>(new WSResponseStatus(-6,
							"邮箱已使用。"));
				}
				user.setEmail(email);
			}

			// 修改用户信息时不修改密码
			if (StringUtils.isNotBlank(userDto.getUsername())) {
				user.setUsername(userDto.getUsername());
			}
			if (StringUtils.isNotBlank(email)) {
				user.setEmail(email);
			}
			user.setAnswer(userDto.getAnswer());
			user.setQuestionId(userDto.getQuizId());
			user.setNickName(userDto.getNickName());
			userManager.saveUser(user);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called updateUser method error", e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("updateAvatar")
	public WSResponse<String> updateUserAvatar(
			@FormParam("userId") String userId, @FormParam("url") String avatar) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != avatar) : "avatar cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user != null) {
				user.setAvatar(avatar);
				userManager.saveUser(user);
				return new WSResponse<String>();
			} else {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called updateUserAvatar method error userId:"
					+ userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("changePassword")
	public WSResponse<String> changePassword(
			@FormParam("username") String username,
			@FormParam("oldPassword") String oldPassword,
			@FormParam("newPassword") String newPassword) {
		assert (null != username) : "username cann't be null.";
		assert (null != oldPassword) : "oldPassword cann't be null.";
		assert (null != newPassword) : "newPassword cann't be null.";
		try {
			User user = userManager.getUserByName(username);
			if (user == null) {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			if (userManager.changePassword(username, oldPassword, newPassword)) {
				return new WSResponse<String>();
			} else {
				return new WSResponse<String>(new WSResponseStatus(-1,
						"该用户不存在或旧密码不匹配"));
			}
		} catch (RuntimeException e) {
			logger.error("called changePassword method error username:"
					+ username, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("resetPassword")
	public WSResponse<String> resetPassword(
			@FormParam("username") String username) {
		assert (null != username) : "username cann't be null.";
		try {
			User user = userManager.getUserByName(username);
			if (user == null) {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
			if (StringUtils.isBlank(user.getEmail())) {
				return new WSResponse<String>(new WSResponseStatus(-2,
						"该用户的邮箱不存在"));
			}
			userManager.startResetPassword(user);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error("called resetPassword method error username:"
					+ username, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("deleteAvatar")
	public WSResponse<String> deleteUserAvatar(
			@FormParam("username") String username) {
		assert (null != username) : "username cann't be null.";
		try {
			User user = userManager.getUserByName(username);
			if (user != null) {
				user.setAvatar("");
				userManager.saveUser(user);
				return new WSResponse<String>();
			} else {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called deleteUserAvatar method error username:"
					+ username, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("postEvent")
	public WSResponse<String> postEvent(@FormParam("userId") String userId,
			@FormParam("eventType") String eventType,
			@FormParam("eventContent") String eventContent) {
		assert (null != userId) : "userId cann't be null.";
		assert (null != eventType) : "eventType cann't be null.";
		assert (null != eventContent) : "eventContent cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user != null) {
				UserEvent userEvent = new UserEvent();
				userEvent.setUser(user);
				userEvent.setType(eventType);
				userEvent.setContent(eventContent);
				userManager.saveUserEvent(userEvent);
				return new WSResponse<String>();
			} else {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called postEvent method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("listEvent")
	public WSResponse<String> listEvent(@FormParam("userId") String userId) {
		assert (null != userId) : "userId cann't be null.";
		try {
			User user = userManager.getUser(userId);
			if (user != null) {
				return new WSResponse<String>();
			} else {
				return new WSResponse<String>(
						new WSResponseStatus(-1, "该用户不存在"));
			}
		} catch (RuntimeException e) {
			logger.error("called listEvent method error userId:" + userId, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	@POST
	@Path("login")
	public WSResponse<String> getTicketGrantingTicket(
			@FormParam("username") String username,
			@FormParam("password") String password) {
		assert (null != username) : "username cann't be null.";
		assert (null != password) : "password cann't be null.";
		if (logger.isDebugEnabled()) {
			logger.debug("Gets a ticket(TGT) by " + uri.getRequestUri());
		}
		String grantingTicketId = null;
		try {
			// 获取Ticket
			Credentials credentials = createUserCredentials(username, password);

			grantingTicketId = centralAuthenticationService
					.createTicketGrantingTicket(credentials);
			// Ticket添加到cookie
			this.ticketGrantingTicketCookieGenerator.addCookie(request,
					response, grantingTicketId);
			return new WSResponse<String>(grantingTicketId);
		} catch (TicketException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Gets a granting ticket", ex);
			}
			return new WSResponse<String>(new WSResponseStatus(-1, "用户名或密码错误。"));
		} catch (RuntimeException e) {
			logger.error(
					"called getTicketGrantingTicket method error username:"
							+ username, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("getServiceTicket")
	public WSResponse<String> getServiceTicket(
			@FormParam("grantingTicket") String grantingTicket,
			@FormParam("service") String service) {
		assert (null != grantingTicket) : "TicketGrantingTicket cann't be null.";
		if (logger.isDebugEnabled()) {
			logger.debug("Gets a ticket(ST) by " + uri.getRequestUri());
		}
		String serviceTicketId = null;
		try {

			SimpleWebApplicationServiceImpl appService = new SimpleWebApplicationServiceImpl(
					genService(service), httpClient);
			serviceTicketId = centralAuthenticationService.grantServiceTicket(
					grantingTicket, appService);
			return new WSResponse<String>(serviceTicketId);
		} catch (TicketException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Grants a ticket(ST) by a TGT", ex);
			}
			return new WSResponse<String>(new WSResponseStatus(-1,
					"非法票据或票据已过时。"));
		} catch (RuntimeException e) {
			logger.error("called getServiceTicket method error grantingTicke:"
					+ grantingTicket, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("validateServiceTicket")
	public WSResponse<String> validateServiceTicket(
			@FormParam("serviceTicket") String serviceTicket,
			@FormParam("service") String service) {
		assert (null != serviceTicket) : "ServiceTicket cann't be null.";
		if (logger.isDebugEnabled()) {
			logger.debug("Validates a ticket(ST) by " + uri.getRequestUri());
		}

		try {
			SimpleWebApplicationServiceImpl appService = new SimpleWebApplicationServiceImpl(
					genService(service), httpClient);

			org.jasig.cas.validation.Assertion assertion = centralAuthenticationService
					.validateServiceTicket(serviceTicket, appService);

			String username = assertion.getChainedAuthentications().get(0)
					.getPrincipal().getId();
			return new WSResponse<String>(username);
		} catch (TicketException ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Grants a ticket(ST) by a TGT", ex);
			}
			return new WSResponse<String>(new WSResponseStatus(-1,
					"非法票据或票据已过时。"));
		} catch (RuntimeException e) {
			logger.error(
					"called validateServiceTicket method error serviceTicket:"
							+ serviceTicket, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}
	}

	@POST
	@Path("logout")
	public WSResponse<String> destoryTicketGrantingTicket(
			@FormParam("grantingTicket") String grantingTicket) {
		assert (null != grantingTicket) : "TicketGrantingTicket cann't be null.";
		if (logger.isDebugEnabled()) {
			logger.debug("Destorys a ticket(TGT) by " + uri.getRequestUri());
		}
		try {
			centralAuthenticationService
					.destroyTicketGrantingTicket(grantingTicket);
			return new WSResponse<String>();
		} catch (RuntimeException e) {
			logger.error(
					"called destoryTicketGrantingTicket method error grantingTicket:"
							+ grantingTicket, e);
			return new WSResponse<String>(WSResponseStatus.SERVER_ERROR);
		}

	}

	protected Credentials createUserCredentials(String username, String password) {
		UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();
		credentials.setUsername(username);
		credentials.setPassword(password);
		return credentials;
	}

	protected String genService(String service) {
		String originalUrl = request.getParameter(PARAM_SERVICE_URL);
		if (StringUtils.isNotBlank(originalUrl)) {
			return originalUrl;
		}
		if (defaultService != null) {
			return defaultService;
		}
		UriBuilder absoluteUriBuilder = UriBuilder.fromUri(request
				.getRequestURL().toString());
		String contextPath = request.getContextPath();

		defaultService = absoluteUriBuilder.replacePath(
				contextPath + DEFAULT_SERVICE_PATH_INFO).build().toString();
		return defaultService;

	}

	protected List<UserDto> toDto(List<User> users) {
		List<UserDto> list = new ArrayList<UserDto>(users.size());
		if (users != null && users.isEmpty()) {
			Iterator<User> iter = users.iterator();
			while (iter.hasNext()) {
				UserDto dto = toDto(iter.next());
				list.add(dto);
			}
		}
		return list;
	}

	protected UserDto toDto(User user) {
		UserDto dto = new UserDto();
		BeanUtils.copyProperties(user, dto);
		return dto;
	}

	private boolean isValidUsername(String username) {
		if (StringUtils.isBlank(username)) {
			return false;
		}
		// 计算中英文混合用户名长度
		int asciiLength = com.google.code.sip.core.utils.StringUtils
				.getAsciiLength(username);
		if (asciiLength < 3 || asciiLength > 15) {
			return false;
		}
		return StringRegexUtils.isUsername(username);

	}

	private boolean isUsernameHasBadword(String username) {
		return false;
	}

	private boolean isValidPassword(String password) {
		if (password.length() < 6) {
			return false;
		}
		return true;
	}

	private boolean isValidEmail(String email) {
		return StringRegexUtils.isEmail(email);
	}

	private boolean isEmailInBlacklist(String email) {
		return false;
	}
}
